<?php

function shushengyuan_qr_login_callback($qr) {
  //0 登录成功 1 继续等待 2 过期
  $timer = 5;
  do {
    sleep(1);
    $timer--;
    $cid = 'pc_login_' . $qr;
    $cache = cache_get($cid, 'cache_shushengyuan');
    if (!empty($cache)) {
      if ($cache->expire >= REQUEST_TIME) {
        if ($cache->data != 0) {
          $uid = $cache->data;
          $account = user_load($uid);
          if (!empty($account)) {
            global $user;
            $user = $account;
            user_login_finalize();
          }
          cache_clear_all($cid, 'cache_shushengyuan');
          $result = ['code' => 0];
          drupal_json_output($result);
          drupal_exit();
        }
        continue;
      }
    }
    $result = ['code' => 2];
    drupal_json_output($result);
    drupal_exit();
  } while ($timer > 0);
  $result = ['code' => 1];
  drupal_json_output($result);
}

function shushengyuan_qr_login_qr() {
  $data = REQUEST_TIME . drupal_random_key();
  $cid = 'pc_login_' . $data;
  cache_set($cid, 0, 'cache_shushengyuan', REQUEST_TIME + 61);
  $url = qr_create_url($data);
  $result = ['code' => 0, 'url' => $url, 'qr' => $data];
  drupal_json_output($result);
}

function shushengyuan_clear_page() {
  module_load_include('inc', 'shushengyuan', 'shushengyuan.forms');
  return drupal_get_form('shushengyuan_clear_form');
}

function shushengyuan_dev_page() {
  $p = \Drupal\shushengyuan\Schemas\ProductItemInfo::init(54, FALSE, [1]);
  dpm($p['poster']);
  return t("<img src='@src'/>", ['@src' => $p['poster']]);
}


function shushengyuan_verification_service_page() {
  module_load_include('inc', 'shushengyuan', 'shushengyuan.forms');
  return drupal_get_form('shushengyuan_verification_service_form');
}
